package com.rc.saas.tenant.controller.parking;

import com.alibaba.excel.EasyExcel;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.rc.saas.tenant.base.BaseSearch;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.redis.RedisLoader;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.parking.ElecParkingOrder;
import com.rc.saas.tenant.model.parking.TenantParkingSupplier;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.parking.ElecParkingOrderSearch;
import com.rc.saas.tenant.service.parking.ElecParkingOrderService;
import com.rc.saas.tenant.service.parking.TenantParkingSupplierService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.parking.ElecParkingOrderExportVo;
import com.rc.saas.tenant.vo.parking.ElecParkingOrderVo;
import com.rc.saas.tenant.vo.parking.TJDUnbindInfo;
import com.rc.saas.tenant.vo.parking.TJDUnbindResult;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Controller
@RequestMapping("/parkingOrderInfo")
public class ParkingOrderInfoController {
    private static Logger logger = LoggerFactory.getLogger(ParkingController.class);

    @Autowired
    private RedisLoader redisLoader;

    @Autowired
    private ElecParkingOrderService elecParkingOrderService;

    @Autowired
    private TenantParkingSupplierService tenantParkingSupplierService;


    @RequestMapping(value = "/parkingOrderInfo",method = RequestMethod.GET)
    public String index(Model model, BaseSearch baseSearch){
        return  "/templates/parking/parkingOrderInfo";
    }

    @ResponseBody
    @RequestMapping(value = "/listPageParkingOrder", method = RequestMethod.GET)
    public WebPageInfo listPageParkingOrder(ElecParkingOrderSearch elecParkingOrderSearch){
        PageInfo<ElecParkingOrderVo> pageInfo = elecParkingOrderService.listPageParkingOrder(elecParkingOrderSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    @ResponseBody
    @RequestMapping(value = "/exportParkingOrder", method = RequestMethod.GET)
    public TResponse exportParkingOrder(ElecParkingOrderSearch elecParkingOrderSearch, HttpServletResponse response){
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel");
        ExportUtils.setDefaultPaging(elecParkingOrderSearch);
        if (elecParkingOrderSearch.getCount() == 0 || elecParkingOrderSearch.getCount() == null) {
            elecParkingOrderSearch.setCount(elecParkingOrderSearch.getLimit());
        }
        if (elecParkingOrderSearch.getCount() > 150000) {
            return TResponse.FAIL("最多导出十五万数据");
        }

        if (elecParkingOrderSearch.getCount() >= 100000) {
            String exportData = (String) redisLoader.get("saas:exportData");
            if (exportData != null) {
                return TResponse.FAIL("导出人数过多,请稍后重试");
            }
            TenantUser user = ShiroUtils.getSessionUser();
            redisLoader.set("saas:exportData", user.getTenantCode(), 1000 * 20);
        }

        //导出拼接开始条数
        elecParkingOrderSearch.setOffset(elecParkingOrderSearch.getLimit() * (elecParkingOrderSearch.getOffset() - 1));

        List<ElecParkingOrderExportVo> list = elecParkingOrderService.listElecParkingOrder(elecParkingOrderSearch);

        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = null;
        try {
            fileName = URLEncoder.encode("道闸停车场订单表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), ElecParkingOrderExportVo.class).sheet("道闸停车场订单表").doWrite(list);
            return TResponse.SUCCESS();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    //解绑优惠券
    @ResponseBody
    @RequestMapping(value = "/unbind_TJD", method = RequestMethod.POST)
    public TResponse unbind_TJD(String outTradeNum, String outTicketNum, Long parkingOrderId, Long parkingSupplierId) {
        try {
            TenantParkingSupplier tenantParkingSupplier = tenantParkingSupplierService.selectByPrimaryKey(parkingSupplierId);
            TJDUnbindInfo tjdUnbindInfo = elecParkingOrderService.assembleTJDParkOrderInfoReq(outTradeNum, outTicketNum, tenantParkingSupplier);

            ObjectMapper objectMapper = new ObjectMapper();
            String jsonData = objectMapper.writeValueAsString(tjdUnbindInfo);
            System.out.println(jsonData);
            logger.info("unbind_TJD:{}", jsonData);
            TJDUnbindResult tjdUnbindResult = Request.Post(tenantParkingSupplier.getUrl())
                    .addHeader("Content-Type", "application/json;charset=UTF-8")
                    .body(new StringEntity(jsonData, "utf-8"))
                    .execute()
                    .handleResponse(new ResponseHandler<TJDUnbindResult>() {
                        @Override
                        public TJDUnbindResult handleResponse(HttpResponse httpResponse) throws IOException {
                            int code = httpResponse.getStatusLine().getStatusCode();
                            if (code == 200) {
                                String result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
                                logger.info("outTradeNum:{},parkingOrderInfo.unbind_TJD:{},TJDParkOrderInfoResult:{}",outTradeNum, tenantParkingSupplier.getUrl(), result);
                                if (StringUtils.isBlank(result)) {
                                    return null;
                                }
                                return new Gson().fromJson(result, TJDUnbindResult.class);
                            } else {
                                logger.error("outTradeNum:{},parkingOrderInfo.unbind_TJD:{}",outTradeNum, EntityUtils.toString(httpResponse.getEntity()));
                                return null;
                            }
                        }
                    });
            if (tjdUnbindResult != null) {
                if ("0".equals(tjdUnbindResult.getIsSuccess())) {
                    ElecParkingOrder elecParkingOrder = elecParkingOrderService.selectByPrimaryKey(parkingOrderId);
                    if ("0".equals(elecParkingOrder.getOrderType())){
                        elecParkingOrder.setOutOrderStatus("2");
                    }
                    elecParkingOrderService.updateByPrimaryKeySelective(elecParkingOrder);
                    logger.info("parkingOrderInfo.unbind_TJD成功,outTradeNum:{}", outTradeNum);
                    return TResponse.SUCCESS("查询成功");
                } else {
                    logger.info("parkingOrderInfo.unbind_TJD失败,outTradeNum:{},returnCode:{},returnMsg:{},errorMsg:{}",
                            outTradeNum,tjdUnbindResult.getReturnCode(),tjdUnbindResult.getReturnMSG(),tjdUnbindResult.getErrorMSG());
                    return TResponse.FAIL(tjdUnbindResult.getErrorMSG());
                }
            }
            logger.info("parkingOrderInfo.unbind_TJD失败,outTradeNum:{},响应信息为空", outTradeNum);
            return TResponse.FAIL("解绑失败");
        } catch (Exception e) {
            logger.error("parkingOrderInfo.unbind_TJD异常,outTradeNum:{},errorMessage:{}",outTradeNum, e.getMessage());
            return TResponse.FAIL("解绑失败");
        }
    }

}
